/*
 * Copyright (C) 2018 xuexiangjys(xuexiangjys@163.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xdlink.core.function.impl;

import android.support.annotation.NonNull;

import com.xuexiang.xdlink.core.function.IDataSaver;
import com.xuexiang.xdlink.logs.DCFLog;
import com.xuexiang.xdlink.util.Utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * 默认数据保存者
 *
 * @author xuexiang
 * @since 2018/8/26 下午6:28
 */
public class DefaultDataSaver implements IDataSaver {

    /**
     * 是否开启数据保存
     */
    private volatile boolean mIsTurnOn;

    /**
     * 保存原始文件的输出流
     */
    private FileOutputStream mFos;

    /**
     * 数据保存的目标文件
     */
    private File mSaveFile;

    /**
     * 构造方法
     *
     * @param saveDirPath 数据存储的目录
     * @param fileName    数据存储的文件名
     */
    public DefaultDataSaver(@NonNull String saveDirPath, @NonNull String fileName) {
        this(new File(saveDirPath, fileName));
    }

    /**
     * 构造方法
     *
     * @param saveFile 数据存储的文件
     */
    public DefaultDataSaver(@NonNull File saveFile) {
        mSaveFile = saveFile;
        DCFLog.i("Data save path：" + saveFile.getAbsolutePath());
        try {
            mFos = new FileOutputStream(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
            DCFLog.e(e);
        }
    }

    @Override
    public void switchStatus(boolean isTurnOn) {
        mIsTurnOn = isTurnOn;
    }

    @Override
    public void saveData(byte[] data, int available) {
        if (mFos != null && mIsTurnOn) {
            try {
                mFos.write(data, 0, available); // 保存数据
            } catch (IOException e) {
                e.printStackTrace();
                DCFLog.e(e);
            }
        }
    }

    @Override
    public boolean cancelSave() {
        recycle();
        return Utils.deleteFile(mSaveFile);
    }

    @Override
    public void recycle() {
        mIsTurnOn = false;
        Utils.closeIO(mFos);
        mFos = null;
    }
}
